﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace ControleRepresentante.Common
{
    public static class EnumExtensionHelper
    {
        public static string GetDescription(this Enum value)
        {
            return GetDescription(value, value.GetType());
        }

        public static string GetDescription(object value, Type type)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            string description = value.ToString();
            FieldInfo fieldInfo = type.GetField(description);

            DescriptionAttribute[] descriptionAttributeCollection =
                (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (descriptionAttributeCollection != null
                && descriptionAttributeCollection.Length > 0)
            {
                description = descriptionAttributeCollection[0].Description;
            }

            return description;
        }

        public static TEnum ParseToEnum<TEnum>(this string value)
        {
            try
            {
                return (TEnum)Enum.Parse(typeof(TEnum), value);
            }
            catch (ArgumentException)
            {
                foreach (object enumItem in Enum.GetValues(typeof(TEnum)).Cast<TEnum>())
                {
                    if (GetDescription((Enum)enumItem) == value)
                    {
                        return (TEnum) enumItem;
                    }
                }
                throw new Exception(string.Format("Unable to convert '{0}' to '{1}'",
                                                  value, typeof (TEnum).FullName));
            }
        }
    }
}
